/*
 * @Author: Leo
 * @Date: 2021-12-08 11:40:44
 * @LastEditors: Leo
 * @LastEditTime: 2021-12-10 14:19:35
 * @Description: file content
 */
import $ from 'jquery'

const requestUrl = "https://demo.zhdoit.com/api/amazonmws/reportPageTask/"
const date = new Date()
console.log(`定时任务开启：${date}`)

setInterval(() => {
  chrome.storage.local.get(['data'], v => {
    const timeData = JSON.parse(v.data)
    if (!timeData || timeData.length <= 0) {
      console.log(`定时任务：${timeData.length}`)
      chrome.storage.local.get(['userData'], userData => {
        $.ajax({
          url: `${requestUrl}list?r=${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()},${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`,
          type: 'POST',
          contentType: 'application/json;charset=utf8',
          headers: {
            'Authorization': userData.userData.token
          },
          success(result) {
            if (result.msg === 'OK' && result.data.length > 0) {
              // 有新任务时
              chrome.storage.local.set({
                "taskNum": result.data.length
              });
              chrome.storage.local.set({
                "taskNum": result.data.length
              })

              chrome.storage.local.set({
                "goRsb": "0",
                "data": JSON.stringify(result.data)
              })

              // eslint-disable-next-line no-inner-declarations
              function sendMessageToContentScript(message, callback) {
                chrome.tabs.query({
                  active: true
                }, tabs => {
                  chrome.tabs.sendMessage(tabs[0].id, message, response => {
                    if (callback) callback(response)
                  })
                })
              }
              sendMessageToContentScript({
                cmd: 'hasData',
                value: result.data
              })
            }
          },
          error(result) {
            console.log(`error:${result}`)
          }
        })
      })
    }
  })
}, 5 * 60 * 1000)

// 监听是否在亚马逊页面，如果是则显示插件图标，否则隐藏
chrome.runtime.onInstalled.addListener(() => {
  chrome.declarativeContent.onPageChanged.removeRules(undefined, () => {
    chrome.declarativeContent.onPageChanged.addRules([{
      conditions: [
        // 只有打开亚马逊才显示pageAction
        new chrome.declarativeContent.PageStateMatcher({
          pageUrl: {
            urlContains: 'sellercentral.amazon.co.uk'
          }
        }),
        new chrome.declarativeContent.PageStateMatcher({
          pageUrl: {
            urlContains: 'sellercentral.amazon.com'
          }
        })
      ],
      actions: [new chrome.declarativeContent.ShowPageAction()]
    }])
  })
})

// 监听来自content-script的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  // 登录通知
  if (request.login === 'notify') {
    chrome.storage.local.get(["isLoad"], r => {
      console.log(`isLoad：${r.isLoad}`)
    });
    chrome.storage.local.get(['taskId'], t => {
      $.ajax({
        url: 'https://demo.zhdoit.com/api/amazonmws/reportPageTask/notify',
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify({
          "notifyContent": "bsr报表插件检测到需要登录，请您前往亚马逊页面进行登录",
          "taskId": t.taskId
        }),
        contentType: 'application/json;charset=utf8',
        success(result) {
          console.log(`success:${result}`)
        }
      })
    });
    sendResponse('已收到，正在通知')
    return
  }
  console.log(request)
  // 下载通知
  const fileName = `${request.reportType}_${request.curCountry}_${request.sellerId}_${request.countryCode}_${request.taskId}_${request.curDate}.csv`
  let fileUrl = ''
  sendResponse(`已收到：${  JSON.stringify(request)}`)

  // 将文件转base64位
  function downloadUrlFile(url) {
    const url2 = url.replace(/\\/g, '/');
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url2, true);
    xhr.responseType = 'blob';
    xhr.onload = () => {
      if (xhr.status === 200) {
        // 获取文件blob数据并保存
        const reader = new FileReader()
        reader.onload = e => {
          fileUrl = e.target.result
          console.log(`${request.curDate}:${e.target.result}`)
        }
        reader.readAsDataURL(xhr.response)
      }
    }
    xhr.send()
  }
  downloadUrlFile(request.url)

  // 下载文件并且更换文件名称
  chrome.downloads.download({
    url: request.url,
    conflictAction: "overwrite",
    filename: fileName
  }, res => {
    // 向popup.html发送当前下载任务
    chrome.storage.local.set({
      'fileName': fileName
    })

    // 抓取当前下载任务状态
    const timeout = setInterval(() => {
      chrome.downloads.search({ id: res }, (data) => {
        console.log(data[0].state)
        if (data[0].state === "complete") {
          clearInterval(timeout)
          // 浏览器右下角提示
          chrome.notifications.create(null, {
            type: 'basic',
            iconUrl: 'img/icon.png',
            title: '下载成功!',
            message: `下载文件：${fileName}`
          })
          console.log(`下载完成！${data[0]}`)

          // chrome.storage.local.set({"isLoad":0});
          // 发送下载成功文件到已下载任务列表中
          chrome.storage.local.get(["fileList"], getfl => {
            const fileNum = 100
            if (getfl.fileList) {
              // 文件列表展示不允许超过100
              if(getfl.fileList.length >= fileNum) {
                // eslint-disable-next-line no-param-reassign
                getfl.fileList = getfl.fileList.slice(0, fileNum)
              }
              // eslint-disable-next-line no-param-reassign
              getfl.fileList = getfl.fileList.push(fileName)
              chrome.storage.local.set({ "fileList": getfl.fileList })
            } else {
              chrome.storage.local.set({ "fileList": [fileName] })
            }
          });

          // 更新当前任务状态

          const updateData = {
            taskId: request.taskId,
            base64FileUrl: fileUrl,
            taskStatus: "2"
          };
          $.ajax({
            url: `${requestUrl}update`,
            data: JSON.stringify(updateData),
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json;charset=utf8',
            success(result) {
              // 完成此次任务
              if (result.code === 0 && result.msg === "OK") {
                console.log(result.msg)
                chrome.storage.local.get(['userData'], userData => {
                  $.ajax({
                    url: `${requestUrl}list`,
                    type: 'POST',
                    contentType: 'application/json;charset=utf8',
                    headers: {
                      'Authorization': userData.userData.token
                    },
                    success(response) {
                      if (response.msg === 'OK') {
                        chrome.storage.local.set({
                          "goRsb": "0",
                          "taskNum": response.data.length,
                          "data": JSON.stringify(response.data)
                        });

                        // eslint-disable-next-line no-inner-declarations
                        function sendMessageToContentScript(message, callback) {
                          chrome.tabs.query({
                            active: true
                          }, tabs => {
                            chrome.tabs.sendMessage(tabs[0].id, message, resp => {
                              if (callback) callback(resp)
                            })
                          })
                        }
                        sendMessageToContentScript({
                          cmd: 'hasData',
                          value: result.data
                        });
                      }
                    },
                    error(err) {
                      console.log(`error:${err}`)
                    }
                  })
                })
              }
            },
            error(err) {
              console.error(err)
            }
          })
        } else if (data[0].state === "interrupted") {
          chrome.storage.local.set({
            "isLoad": 0,
            "fileName": ''
          })
          clearInterval(timeout)
          // eslint-disable-next-line no-alert
          alert("下载中断，出现错误！")
        }
      })
    }, 3000)
  })
})
